package controller

import (
	"github.com/gin-gonic/gin"
	"kf/models/dao"
	"kf/utils/R"
	"kf/ws"
	"net/http"
	"strconv"
)

type KefuController struct {
	SysUserDao    *dao.SysUserDao
	UserClientDao *dao.UserClientDao
	UserRolesDao  *dao.SysUserRolesDao
	VisitorsDao   *dao.VisitorsDao
	MessageDao    *dao.MessageDao
	WsVisitor     *ws.WsVisitor
}

func (kefuController *KefuController) PostKefuClient(c *gin.Context) {
	kefuName, _ := c.Get("kefu_name")
	clientId := c.PostForm("client_id")

	if clientId == "" {
		c.JSON(http.StatusOK, R.ReturnFailMsg("client_id不能为空"))
		return
	}
	kefuController.UserClientDao.CreateUserClient(kefuName.(string), clientId)
	c.JSON(http.StatusOK, R.ReturnSuccessMsg("ok"))
}

func (kefuController *KefuController) GetOtherKefuList(c *gin.Context) {
	idStr, _ := c.Get("kefu_id")
	id := idStr.(float64)
	result := make([]interface{}, 0)
	ws.SendPingToKefuClient()
	kefus, err := kefuController.SysUserDao.FindUsers()
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg("获取客服信息失败"))
		return
	}
	for _, kefu := range kefus {
		if uint64(id) == kefu.ID {
			continue
		}

		item := make(map[string]interface{})
		item["name"] = kefu.UserName
		item["nickname"] = kefu.NickName
		item["avator"] = kefu.Avatar
		item["status"] = "offline"
		kefu, ok := ws.KefuList[strconv.FormatUint(kefu.ID, 10)]
		if ok && kefu != nil {
			item["status"] = "online"
		}
		result = append(result, item)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": result,
	})
}

func (kefuController *KefuController) PostTransKefu(c *gin.Context) {
	kefuId := c.Query("kefu_id")
	visitorId := c.Query("visitor_id")
	curKefuId, _ := c.Get("kefu_name")
	user, err := kefuController.SysUserDao.FindSysUserById(kefuId)
	visitor := kefuController.VisitorsDao.FindVisitorByVisitorId(visitorId)
	if err != nil || user.UserName == "" || visitor.Name == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "访客或客服不存在",
		})
		return
	}
	kefuController.VisitorsDao.UpdateVisitorKefu(visitorId, kefuId)
	ws.UpdateVisitorUser(visitorId, kefuId)
	go kefuController.WsVisitor.VisitorOnline(kefuId, visitor)
	go kefuController.WsVisitor.VisitorOffline(curKefuId.(string), visitor.VisitorId, visitor.Name)
	go kefuController.WsVisitor.VisitorNotice(visitor.VisitorId, "客服转接到"+user.NickName)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "转移成功",
	})
}
func (kefuController *KefuController) GetKefuInfoSetting(c *gin.Context) {
	kefuId := c.Query("kefu_id")
	user, err := kefuController.SysUserDao.FindSysUserById(kefuId)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg("获取用户信息失败"))
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": user,
	})
	return
}
